var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const app = getApp();
let latitude = ''; //纬度
let longitude = ''; //纬度
let accuracy = ''; //位置精度
let speed = ''; //速度
let positioningType = '';
let positioningStyle = '';
let updateFlag = false; //是否更新过用户信息
var isClick = true;
import {authUserPhone} from "../../../utils/publicMethods";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0, //顶部高度
    bnt: 0, //按钮显示0-灰色；1-彩色
    ani: 0, //动画是否执行
    getUserinfo: '', //是否拉取用户信息
    isSetting: 0, //是否打开设置
    readRule: 0, //阅读活动规则勾选
    readPrivate: 0, //阅读隐私政策勾选
    isShow: 1, //同意按钮默认显示
    isShowModalRule: false, //是否显示阅读规则遮罩
    isShowModalPriv: false, //是否显示隐私政策遮罩
    isShowModalAuth: false, //是否显示授权遮罩
    canIUseGetUserProfile: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    try {
      // 检测是否可以调用getUpdateManager检查更新
      if (!wx.canIUse("getUpdateManager")) return;
      let updateManager = wx.getUpdateManager();
      // 获取全局唯一的版本更新管理器，用于管理小程序更新
      updateManager.onCheckForUpdate(function (res) {
        log.info(res) 
     
        console.log(res.hasUpdate)
        // 监听向微信后台请求检查更新结果事件
        log.info("是否有新版本：" + res.hasUpdate);
        if (res.hasUpdate) {
          //如果有新版本
          // 小程序有新版本，会主动触发下载操作
          updateManager.onUpdateReady(function () {
            //当新版本下载完成，会进行回调
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，单击确定重启小程序',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                  updateManager.applyUpdate();
                }
              }
            })
          })
          // 小程序有新版本，会主动触发下载操作（无需开发者触发）
          updateManager.onUpdateFailed(function () {
            //当新版本下载失败，会进行回调
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请稍后尝试',
              showCancel: false,
            })
          })
        }
      });
    } catch (e) {
      e
    }
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight,
      getUserinfo: wx.getStorageSync('getUserinfo'),
      getPhone: wx.getStorageSync('getPhone'),
      icon:wx.getStorageSync('productType')==4?'xinyouranPage/loading_logo':'common/loading',
    });
  
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // 获取jsCode
    this.updateJSCode();
  },
  updateJSCode() {
    wx.login({
      success: res => {
        console.log("[onLoad--wx.login]" + res);
        if (res.code) {
          wx.setStorageSync('code', res.code)
        } else {
          console.log("获取jsCode失败" + res.errMsg);
        }
      }
    });
  },
  /**
   * 勾选、取消活动规则
   */
  onClickRule: function () {
    let readRule = this.data.readRule;
    if (readRule) {
      this.setData({
        readRule: 0
      })
    } else {
      this.setData({
        readRule: 1
      })
    }
    this.sureBnt();
  },
  /**
   * 勾选、取消隐私政策
   */
  onClickPrivate: function () {
    let readPrivate = this.data.readPrivate;
    if (readPrivate) {
      this.setData({
        readPrivate: 0
      })
    } else {
      this.setData({
        readPrivate: 1
      })
    }

    this.sureBnt();
  },

  //点击活动规则
  readRuleLink: function () {
    wx.navigateTo({
      url: '../ruleh5/ruleh5'
    })
  },
  //点击隐私政策
  readPrivateLink: function () {
    this.setData({
      isShowModalPriv: 1
    }); //显示
  },
  //关闭活动规则和隐私政策
  clickClose: function (event) {
    const that = this;
    //关闭，启动动画效果
    that.setData({
      ani: 1
    });
    //延时关闭，等动画加载完毕后再关闭
    setTimeout(function () {
      let isRule = event.currentTarget.dataset.viewpointRule;
      if (isRule == '1') { //同意
        that.setData({
          isShowModalRule: false, //关闭遮罩
          readRule: 1 //已阅读活动规则
        })
      } else if (isRule == '0') { //取消
        //关闭遮罩
        that.setData({
          isShowModalRule: false //关闭遮罩
        })
      }
      let isPriv = event.currentTarget.dataset.viewpointPri;
      if (isPriv == '1') { //同意
        that.setData({
          isShowModalPriv: false, //关闭遮罩
          readPrivate: 1 //已阅读隐私政策
        })
      } else if (isPriv == '0') { //取消
        //关闭遮罩
        that.setData({
          isShowModalPriv: false //关闭遮罩
        })
      }
      that.sureBnt();
      //关闭后，动画停止
      that.setData({
        ani: 0
      });
    }, 180) //延迟时间 这里是0.18秒

  },
  // 取消按钮，跳转首页
  gotoIndex: function () {
    wx.removeStorageSync('qrCode')
    wx.redirectTo({
      url: '../index/index',
    })
  },
  // 按钮改变颜色，当活动规则、隐私政策都勾选时，改变按钮为彩色
  sureBnt() {
    if (this.data.readPrivate & this.data.readRule) {
      this.setData({
        bnt: 1
      })
    } else {
      this.setData({
        bnt: 0
      })
    }
  },
  /**
   * 点击酒瓶或按钮，进行授权或抽奖操作
   */
  onclickBottle: async function () {
    log.info("[index]--->[点击进入]")
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 2000); //3秒内不能重复点击
    }

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    if (wx.getStorageSync('qrCode') == null || wx.getStorageSync('qrCode') == undefined || wx.getStorageSync('qrCode') == '') { //无码用户进入小程序,新用户
      // 无码进入，调用摄像头进行扫码
      api.scanCode();
    } else {
      //扫码抽奖
      this.scanQrcodeApi();
    }
  },
  scanCode() {
    wx.removeStorageSync('qrCode')
    // 无码进入，调用摄像头进行扫码
    api.scanCode();
  },
  /**
   * 调用扫码接口
   */
  scanQrcodeApi: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    this.isLoading(true, "正在获取位置...");
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        that.isLoading(false)
        //存入地址
        latitude = res.latitude;
        longitude = res.longitude;
        speed = res.speed;
        accuracy = res.accuracy;
        wx.setStorageSync('latitude', latitude);
        wx.setStorageSync('longitude', longitude);
        wx.setStorageSync('speed', speed);
        wx.setStorageSync('accuracy', accuracy);
        wx.redirectTo({
          url: '../index/index?source=readRule&longitude=' + longitude + '&latitude=' + latitude,
        })
      },
      fail: res => {
        that.isLoading(false)
        log.error('[wx.getLocation===res.errMsg]' + JSON.stringify(res.errMsg))
        if (res.errMsg) {
          that.setData({
            isShowModalAuth: true,
            authText: "为了保证正常获取奖励，现需获取您的地理位置",
            isSetting: 1
          })
          return;
        }
      }
    })
  },



  /**
   * 用户同意获取用户信息回调
   * @param {*} e 
   */
  async bindGetUserInfo(e) {
    console.log("old头像授权")
    if (this._freshing) return
    this._freshing = true
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    this.setData({
      isLoading: true,
      loadingText: "正在获取信息..."
    })
    const that = this;
    if (e.detail.userInfo) {
      console.log('e.detail.userInfo' + JSON.stringify(e.detail.userInfo));
      //用户按了允许授权按钮
      app.globalData.userInfo = e.detail.userInfo;
      wx.setStorageSync('nickName', e.detail.userInfo.nickName);
      //遮罩层消失
      this.setData({
        isShowModalAuth: 0
      })
      //更新用户信息
      let res = await that.updateUserInfo(e.detail.encryptedData, e.detail.iv);
      that.updateJSCode();
      if (!res) {
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //已成功授权用户信息，并保存
      wx.setStorageSync('getUserinfo', true);

      console.log("开始授权手机号")
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText: "为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1',
      })
      this._freshing = false;
    } else {
      //用户按了拒绝按钮,显示授权遮罩层
      this.setData({
        isShowModalAuth: 1,
        authText: "为了保证正常获取奖励，现需获取您的头像昵称"
      })
      api.cancelLoading();
      this._freshing = false;
      return;
    }


  },

  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    console.log("new头像授权")
    const that = this;
    if (that._freshing) return
    that._freshing = true
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.isLoading(true, "正在获取信息...");
    new Promise(function (resolve, reject) {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('nickName', res.userInfo.nickName);
          wx.setStorageSync('getUserinfo', true);
          //遮罩层消失
          that.setData({
            isShowModalAuth: 0,
            getUserinfo: true,
          })
          that._freshing = false;
          resolve(res);
        },
        fail: (res) => {
          console.log("getUserProfile" + res)
          //用户按了拒绝按钮,显示授权遮罩层
          that.setData({
            isShowModalAuth: 1,
            authText: "为了保证正常获取奖励，现需获取您的头像昵称"
          })
          api.cancelLoading();
          that._freshing = false;
          resolve();
        }

      })
    }).then(
      async function (obj) {
        //更新用户信息
        let res = await that.updateUserInfo(obj.encryptedData, obj.iv);
        that.updateJSCode();
        that.isLoading(false)
        if (!res) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
          })
          return;
        }
        //已成功授权用户信息，并保存
        wx.setStorageSync('getUserinfo', true);

        console.log("开始授权手机号")
        that.setData({ //显示拒绝授权提示层
          isShowModalAuth: true,
          authText: "为了保证正常获取奖励，现需获取您的手机号码",
          isPhone: '1',
        })
      }

    ).catch(() => {
      that.isLoading(false)
      console.log("信息授权失败啦")
    })




  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  async getPhoneNumber(e) {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if(e.detail.errno===1400001){
        wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.PHONENUMERROR.code + '&retMsg=' + apiCode.PHONENUMERROR.msg,
        })
        return;
    }
    this.isLoading(true, "正在获取信息...")
    var that = this;
    if (e.detail.encryptedData != undefined) {
      that.setData({ //同意
        isShowModalAuth: false,
        getPhone: true
      })

      let res = await authUserPhone(e);
      this.updateJSCode();
      that.isLoading(false)
      if (!res) {
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //已成功授权手机号，并保存
      wx.setStorageSync('getPhone', true);
      wx.setStorageSync('getUserinfo', true);
      this.scanQrcodeApi();
    } else {
      that.isLoading(false)
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText: "为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1'
      })

    }
  },

  /**
   * 更新用户信息
   * @param {*} encryptedData 
   * @param {*} iv 
   */
  updateUserInfo(encryptedData, iv) {
    const that = this;
    console.log('updateUserInfo')
    return new Promise((resolve, reject) => {
      netWork.POST('updateUserInfo', {
        data: {
          userId: wx.getStorageSync('userId'),
          encryptedData: encodeURIComponent(encryptedData),
          iv: encodeURIComponent(iv),
          jsCode: wx.getStorageSync('code')
        },
        success: function (res) {
          if (res.data.retCode == undefined) {
            resolve(false);
          }
          if (res.data.retCode == '0000') {
            wx.setStorageSync('userPhone', res.data.data.phone);
            resolve(true);
          } else {
            resolve(false);
          }
        },
        fail: function (res) {
          resolve(false);
        }
      });
    });

  },
  openSetting() {
    this.setData({
      isShowModalAuth: false
    })
    api.putOpenSetting();
  },


  /**
   * 判断是否进行勾选
   */
  onClickSure: function () {
    wx.showToast({
      title: '请阅读并同意活动规则和隐私政策',
      icon: 'none'
    })

  },
  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })
  },
  onShow(){
    try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
    } catch (error) {
        console.info(error)
    }
  }

})